﻿using Elsa.Events;
using MediatR;
using Zhp.SqlSugar.Repository;
using Zhp.Workflow.Activities.DataOptions;
using Zhp.Workflow.Entity;
using Zhp.Workflow.Models;

namespace Zhp.Workflow.Notify
{
    /// <summary>
    /// 流程完成通知提交人
    /// </summary>
    public class WorkflowCompletedHander : INotificationHandler<WorkflowCompleted>
    {
        IBaseRepository<WorkflowNotify> _rep;
        public WorkflowCompletedHander(IBaseRepository<WorkflowNotify> rep)
        {
            _rep = rep;
        }
        /// <summary>
        /// 流程完成
        /// </summary>
        /// <param name="notification"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task Handle(WorkflowCompleted notification, CancellationToken cancellationToken)
        {
            var wf = notification.WorkflowExecutionContext.WorkflowInstance;
            var submiterId = wf.Variables.Get<string>(WorkflowVariables.SubmiterId);
            var submiterName = wf.Variables.Get<string>(WorkflowVariables.SubmiterName);
            var input = notification.WorkflowExecutionContext.Input as ApproveInput;

            var notify = new WorkflowNotify
            {
                SubmitterName = submiterName,
                SubmitterId = Convert.ToInt64(submiterId),
                WorkflowName = wf.Name,
                WorkflowId = wf.Id,
                ModelType = wf.ContextType,
                ModelID = wf.ContextId,
                ApproveStatus = input.Action.ConvertToApproveStatus(),
                ApproveRemark = input.Remark,
                IsSend = false
            };

            await _rep.InsertAsync(notify);
        }

    }
}
